local validate_entity = require("kong.dao.schemas_validation").validate_entity
local oauth2_schema = require "kong.plugins.oauth2.schema"

describe("Plugin: oauth2 (schema)", function()
  it("does not require `scopes` when `mandatory_scope` is false", function()
    local ok, errors = validate_entity({enable_authorization_code = true, mandatory_scope = false}, oauth2_schema)
    assert.True(ok)
    assert.is_nil(errors)
  end)
  it("valid when both `scopes` when `mandatory_scope` are given", function()
    local ok, errors = validate_entity({enable_authorization_code = true, mandatory_scope = true, scopes = {"email", "info"}}, oauth2_schema)
    assert.True(ok)
    assert.is_nil(errors)
  end)
  it("autogenerates `provision_key` when not given", function()
    local t = {enable_authorization_code = true, mandatory_scope = true, scopes = {"email", "info"}}
    local ok, errors = validate_entity(t, oauth2_schema)
    assert.True(ok)
    assert.is_nil(errors)
    assert.truthy(t.provision_key)
    assert.equal(32, t.provision_key:len())
  end)
  it("does not autogenerate `provision_key` when it is given", function()
    local t = {enable_authorization_code = true, mandatory_scope = true, scopes = {"email", "info"}, provision_key = "hello"}
    local ok, errors = validate_entity(t, oauth2_schema)
    assert.True(ok)
    assert.is_nil(errors)
    assert.truthy(t.provision_key)
    assert.equal("hello", t.provision_key)
  end)

  describe("errors", function()
    it("requires at least one flow", function()
      local ok, _, err = validate_entity({}, oauth2_schema)
      assert.False(ok)
      assert.equal("You need to enable at least one OAuth flow", tostring(err))
    end)
    it("requires `scopes` when `mandatory_scope` is true", function()
      local ok, errors = validate_entity({enable_authorization_code = true, mandatory_scope = true}, oauth2_schema)
      assert.False(ok)
      assert.equal("To set a mandatory scope you also need to create available scopes", errors.mandatory_scope)
    end)
  end)
end)
